// @ts-nocheck
import { defineBoot } from '#q-app/wrappers';
import axios, { type AxiosInstance } from 'axios';

declare module 'vue' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
    $api: AxiosInstance;
  }
}
import { useUserStore } from "@/stores/use_user_store"
import { Notify, Dialog, Cookies } from "quasar"

// Be careful when using SSR for cross-request state pollution
// due to creating a Singleton instance here;
// If any client changes this (global) instance, it might be a
// good idea to move this instance creation inside of the
// "export default () => {}" function below (which runs individually
// for each client)
const service = axios.create({
  baseURL: process.env.API,
  timeout: 120000,
  withCredentials: false,
})

export default defineBoot(({ app }) => {
  service.interceptors.request.use(
    config => {
      const userStore = useUserStore()
      config.headers = {
        "Content-Type": "application/json",
        "x-token": userStore.token,
        "x-user-id": userStore.userInfo.ID,
        ...config.headers,
      }
      return config
    },
    error => {
      Notify.create({
        type: "negative",
        message: error,
      })
      return Promise.reject(error)
    }
  )

  service.interceptors.response.use(
    response => {
      const userStore = useUserStore()
      if (!response.config.donNotShowLoading) {
        // closeLoading()
      }
      if (response.headers["new-token"]) {
        userStore.setToken(response.headers["new-token"])
      }
      if (response.data.code === 0 || response.headers.success === "true") {
        if (response.headers.msg) {
          response.data.msg = decodeURI(response.headers.msg)
        }
        return response.data
      } else {
        console.log(`service.interceptors 出错 response  👉`, response)
        Notify.create({
          type: "negative",
          message: response.data.msg || decodeURI(response.headers.msg),
        })
        return response.data.msg ? response.data : response
      }
    },
    error => {
      if (!error.config.donNotShowLoading) {
        // closeLoading()
      }

      if (!error.response) {
        Dialog.create({
          title: "请求报错",
          message: `
              <p>检测到请求错误</p>
              <p>${error}</p>
              `,
          html: true,
          ok: {
            label: "稍后重试",
          },
          cancel: {
            label: "取消",
          },
        }).onOk(() => {
          // 这里可以添加稍后重试的逻辑，如果需要
        })
        return
      }

      switch (error.response.status) {
        case 500:
          Dialog.create({
            title: "接口报错",
            message: `
              <p>检测到接口错误${error}</p>
              <p>错误码<span style="color:red"> 500 </span>：此类错误内容常见于后台panic，请先查看后台日志，如果影响您正常使用可强制登出清理缓存</p>
              `,
            html: true,
            ok: {
              label: "清理缓存",
            },
            cancel: {
              label: "取消",
            },
          }).onOk(() => {
            const userStore = useUserStore()
            userStore.ClearStorage()
            router.push({ name: "Login", replace: true })
          })
          break
        case 404:
          console.log(`404 error 👉`, error)
          break
        case 401:
          Dialog.create({
            title: "身份信息",
            message: `
                <p>无效的令牌</p>
                <p>错误码:<span style="color:red"> 401 </span>错误信息:${error}</p>
                `,
            html: true,
            ok: {
              label: "重新登录",
            },
            cancel: {
              label: "取消",
            },
          }).onOk(() => {
            const userStore = useUserStore()
            userStore.ClearStorage()
            router.push({ name: "Login", replace: true })
          })
          break
      }

      return error
    }
  )
  // for use inside Vue files (Options API) through this.$axios and this.$api

  app.config.globalProperties.$axios = axios
  // ^ ^ ^ this will allow you to use this.$axios (for Vue Options API form)
  //       so you won't necessarily have to import axios in each vue file

  app.config.globalProperties.$service = service
  // ^ ^ ^ this will allow you to use this.$api (for Vue Options API form)
  //       so you can easily perform requests against your app's API
})

export { service }
